package com.jlnk.servicedemo.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.Nullable;

import com.jlnk.servicedemo.entity.MediaItem;
import com.jlnk.servicedemo.event.MusicEvent;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CustomService extends Service {
    private MediaPlayer mMediaPlayer;
    private OnMusicPlayStateChangeListener mOnMusicPlayStateChangeListener;
    private List<MediaItem> playlist = new ArrayList<>();
    private int currentSongIndex = 0;
    private int mCurrentPosition;

    private Handler mHandler = new Handler(Looper.getMainLooper());
    private Runnable mProgressUpdateRunnable = new Runnable() {
        @Override
        public void run() {
            if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                int currentPosition = mMediaPlayer.getCurrentPosition();
                int duration = mMediaPlayer.getDuration();
                if (mOnMusicPlayStateChangeListener != null) {
                    mOnMusicPlayStateChangeListener.onProgressUpdate(currentPosition, duration);
                }
                mHandler.postDelayed(this, 1000); // 更新频率为每秒一次
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        initPlayer();
    }

    private void initPlayer() {
        if (mMediaPlayer != null) {
            releaseMediaPlayer();
        }
        mMediaPlayer = new MediaPlayer();
        try {
            // 设置数据源为 null 会导致 MediaPlayer 无法播放，应确保正确设置数据源
            mMediaPlayer.setDataSource("正确的数据源");
            mMediaPlayer.prepareAsync();
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                    EventBus.getDefault().post(new MusicEvent("play"));
                    if (mOnMusicPlayStateChangeListener != null) {
                        mOnMusicPlayStateChangeListener.onPlayStart();
                    }
                    mHandler.post(mProgressUpdateRunnable); // 启动进度更新
                }
            });

            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    updateProgress();
                    EventBus.getDefault().post(new MusicEvent("complete"));
                    if (mOnMusicPlayStateChangeListener != null) {
                        mOnMusicPlayStateChangeListener.onPlayComplete();
                    }
                    next();
                }
            });
            mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    Log.d("asdf", "播放错误: " + what + ", " + extra);
                    releaseMediaPlayer();
                    return true;
                }
            });
        } catch (Exception e) {
            Log.e("CustomService", "Error setting up MediaPlayer", e);
        }
    }

    public void playSong(int resId) {
        if (mMediaPlayer != null) {
            releaseMediaPlayer();
        }
        mMediaPlayer = MediaPlayer.create(this, resId);
        if (mMediaPlayer != null) {
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                    EventBus.getDefault().post(new MusicEvent("play"));
                    if (mOnMusicPlayStateChangeListener != null) {
                        mOnMusicPlayStateChangeListener.onPlayStart();
                    }
                }
            });
            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    Log.d("asdf", "播放结束!");
                    EventBus.getDefault().post(new MusicEvent("complete"));
                    if (mOnMusicPlayStateChangeListener != null) {
                        mOnMusicPlayStateChangeListener.onPlayComplete();
                    }
                    next();
                }
            });
            mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    if (what == MediaPlayer.MEDIA_ERROR_UNKNOWN) {
                        mMediaPlayer.release();
                        mMediaPlayer = null;
                        initPlayer();
                    }
                    return true;
                }
            });
        } else {
            Log.e("CustomService", "MediaPlayer 创建失败");
        }
    }

    public void updateProgress() {
        if (mOnMusicPlayStateChangeListener != null) {
            int currentPosition = mMediaPlayer.getCurrentPosition();
            int duration = mMediaPlayer.getDuration();
            mOnMusicPlayStateChangeListener.onProgressUpdate(currentPosition, duration);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            int resId = intent.getIntExtra("resId", 0);
            if (resId != 0) {
                playSong(resId);
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    public void pause() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            mCurrentPosition = mMediaPlayer.getCurrentPosition(); // 保存当前位置
            mMediaPlayer.pause();
            EventBus.getDefault().post(new MusicEvent("stop"));
            if (mOnMusicPlayStateChangeListener != null) {
                mOnMusicPlayStateChangeListener.onPlayStop();
            }
            stopProgressUpdate();
        }
    }

    public void play() {
        if (mMediaPlayer != null) {
            if (!mMediaPlayer.isPlaying()) {
                if (mMediaPlayer.getCurrentPosition() == 0) {
                    mMediaPlayer.start(); // 如果当前位置为0，则从头开始播放
                } else {
                    mMediaPlayer.seekTo(mCurrentPosition); // 从保存的位置开始播放
                    mMediaPlayer.start();
                }
                EventBus.getDefault().post(new MusicEvent("play"));
                if (mOnMusicPlayStateChangeListener != null) {
                    mOnMusicPlayStateChangeListener.onPlayStart();
                }
                startProgressUpdate();
            }
        }
    }

    public void startProgressUpdate() {
        if (mMediaPlayer != null && mHandler != null) {
            mHandler.post(mProgressUpdateRunnable);
        }
    }

    public void stopProgressUpdate() {
        if (mHandler != null) {
            mHandler.removeCallbacks(mProgressUpdateRunnable);
        }
    }

    public void next() {
        if (playlist.size() > 0) {
            currentSongIndex = (currentSongIndex + 1) % playlist.size();
            MediaItem nextItem = playlist.get(currentSongIndex);
            if (nextItem.hasResId()) {
                playSong(nextItem.getResId());
            } else if (nextItem.hasPath()) {
                playSong(nextItem.getPath());
            } else {
                Log.e("CustomService", "Next song path is null");
            }
        } else {
            Log.e("CustomService", "播放列表为空，无法播放下一首歌曲");
        }
    }

    public void last() {
        if (playlist.size() > 0) {
            currentSongIndex = (currentSongIndex - 1 + playlist.size()) % playlist.size();
            MediaItem prevItem = playlist.get(currentSongIndex);
            if (prevItem.hasResId()) {
                playSong(prevItem.getResId());
            } else if (prevItem.hasPath()) {
                playSong(prevItem.getPath());
            } else {
                Log.e("CustomService", "Previous song path is null");
            }
        } else {
            Log.e("CustomService", "播放列表为空，无法播放上一首歌曲");
        }
    }

    public int getDuration() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            return mMediaPlayer.getDuration();
        }
        return 0;
    }

    public int getCurrentPosition() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            return mMediaPlayer.getCurrentPosition();
        }
        return 0;
    }

    public String getSongTitle() {
        if (currentSongIndex >= 0 && currentSongIndex < playlist.size()) {
            MediaItem item = playlist.get(currentSongIndex);
            return item.getTitle();
        }
        return "";
    }

    public String getArtistName() {
        if (currentSongIndex >= 0 && currentSongIndex < playlist.size()) {
            MediaItem item = playlist.get(currentSongIndex);
            return item.getArtist();
        }
        return "";
    }

    public boolean isPlaying() {
        if (mMediaPlayer != null) {
            return mMediaPlayer.isPlaying();
        }
        return false;
    }

    public void seekTo(int progress) {
        if (mMediaPlayer != null) {
            mMediaPlayer.seekTo(progress);
            updateProgress();
        }
    }

    public void setOnMusicPlayStateChangeListener(OnMusicPlayStateChangeListener l) {
        mOnMusicPlayStateChangeListener = l;
    }

    public interface OnMusicPlayStateChangeListener {
        void onPlayStart();
        void onPlayStop();
        void onPlayComplete();
        void onProgressUpdate(int currentPosition, int duration);
    }

    private void releaseMediaPlayer() {
        if (mMediaPlayer != null) {
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
            }
            mMediaPlayer.release();
            mMediaPlayer = null;    }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    public final class MyBinder extends Binder {
        public CustomService getService() {
            return CustomService.this;
        }
    }

    public void setPlaylist(List<MediaItem> playlist) {
        if (playlist != null && !playlist.isEmpty()) {
            this.playlist = playlist;
            this.currentSongIndex = 0;
            MediaItem firstItem = playlist.get(currentSongIndex);
            if (firstItem.hasResId()) {
                playSong(firstItem.getResId());
            } else if (firstItem.hasPath()) {
                playSong(firstItem.getPath());
            } else {
                Log.e("CustomService", "First song path is null and no resource ID");
            }
            Log.d("CustomService", "播放列表已设置");
        } else {
            Log.e("CustomService", "播放列表为空，无法设置");
        }
    }

    public void playSong(String path) {
        if (path == null) {
            Log.e("CustomService", "playSong: path is null");
            return;
        }
        if (mMediaPlayer != null) {
            releaseMediaPlayer();
        }
        mMediaPlayer = new MediaPlayer();
        try {
            mMediaPlayer.setDataSource(getApplicationContext(), Uri.parse(path));
            mMediaPlayer.prepareAsync();
            mMediaPlayer.setOnPreparedListener(mp -> {
                mp.start();
                if (mOnMusicPlayStateChangeListener != null) {
                    mOnMusicPlayStateChangeListener.onPlayStart();
                }
                updateProgress();
                startProgressUpdate();
            });
            mMediaPlayer.setOnCompletionListener(mp -> {
                if (mOnMusicPlayStateChangeListener != null) {
                    mOnMusicPlayStateChangeListener.onPlayComplete();
                }
                next();
            });
            mMediaPlayer.setOnErrorListener((mp, what, extra) -> {
                Log.e("CustomService", "Error: " + what + ", " + extra);
                releaseMediaPlayer();
                return true;
            });
        } catch (IOException e) {
            Log.e("CustomService", "IOException", e);
        }
    }

    @Override
    public void onDestroy() {
        mHandler.removeCallbacks(mProgressUpdateRunnable);
        releaseMediaPlayer();
        super.onDestroy();
    }
}